<template>
  <div class="page">
    <!-- 顶部 -->
    <header class="header">
      <!-- 为logo添加点击事件 -->
      <div class="logo" @click="goHomePage">
        <SvgIcon name="ai-back" size="32" />
      </div>
      <!-- <div class="title">
        <SvgIcon name="ai-logo-title" width="70" height="20" />
      </div> -->
      <div class="name">
        {{ currentTab.name }}
      </div>
      <div class="name aracde" v-if="activityDetail"># {{ activityDetail.title }}</div>
    </header>
    <!-- layout -->
    <main class="layout">
      <div class="tab">
        <div class="publish-btn" @click="openProPublishDialog" v-if="isPro">
          <SvgIcon name="ai-upload-pro" width="72" height="72" />
        </div>
        <div v-for="(group, index) in filteredTabItems" :key="index" class="tab-group">
          <div
            v-for="item in group"
            :key="item.path"
            :id="item.path"
            :class="['tab-item', { active: isActive(item.path) }]"
            @click="navigateTo(item.path)"
            @mouseenter="hoveredItem = item.path"
            @mouseleave="hoveredItem = ''">
            <el-tooltip :content="item.name" placement="right">
              <img :src="loadIcon(getIconName(item))" alt="icon" />
            </el-tooltip>
          </div>
        </div>
      </div>
      <div class="router-view">
        <router-view v-if="rawRoute" />
        <div class="nested-layout" v-else>
          <!-- 左侧内容区域 - 渲染子路由组件 -->
          <div class="content-left" id="content-left">
            <router-view />
          </div>
          <!-- 右侧统一的ImageList区域 -->
          <div class="content-right" id="content-right">
            <ImageList :list="aiStore.results" :showDelete="true" />
          </div>
        </div>
      </div>
    </main>
  </div>
  <PublishDialog
    ref="publishDialogRef"
    v-if="showPublishDialog"
    @close="handleDialogClose"
    :imageList="publishImageList"
    :prompt="promptText"
    :promptMode="promptMode"
    :contestTitle="contestTitle" />
</template>

<script setup lang="ts">
  import { useRoute, useRouter } from 'vue-router';
  import PublishDialog from '@/views/ai/publish.vue';
  import { computed, ref, onMounted, nextTick, watch } from 'vue';
  import SvgIcon from '@/components/SvgIcon.vue';
  import { useUserStore } from '@/store/user';
  import { loadIcon } from '@/views/ai/index';
  import { useBus } from '@/utils/bus';
  import ImageList from '@/views/ai/ImageList.vue';
  import Overlay from '@/components/Overlay.vue';
  import UserGuide from '@/components/UserGuide.vue';
  import { useAiStore } from '@/store/ai';
  import { ActivityAPI } from '@/api/activity';
  import { getElementInfoById } from '@/utils/guideTools';

  // 创建PublishDialog的ref引用
  const publishDialogRef = ref<InstanceType<typeof PublishDialog>>();
  // 控制PublishDialog显示的变量
  const showPublishDialog = ref(false);
  // 存储要发布的图片列表
  const publishImageList = ref<string[]>([]);

  const promptMode = ref(true);
  const promptText = ref('');
  const contestTitle = ref('');

  // 定义tab项的类型
  interface TabItem {
    name?: string;
    path: string;
    icon: string;
  }

  // tab项数组 - 添加了名称
  const tabItems: TabItem[][] = [
    [
      { name: 'Text to Image', path: '/generator/txt2img', icon: 'txt' },
      { name: 'Image to Image', path: '/generator/img2img', icon: 'img' },
    ],
    [
      { name: 'Edit Image Details', path: '/generator/edit', icon: 'edit' },
      { name: 'Upscale', path: '/generator/hd', icon: 'hd' },
    ],
    [{ name: 'History', path: '/generator/history', icon: 'history' }],
  ];

  // 计算属性：根据路由参数动态过滤tabItems
  const filteredTabItems = computed(() => {
    // 检查路由是否带有aid参数
    const hasAid = !!route.query.aid;

    if (!hasAid) {
      return tabItems;
    }

    // 如果有aid参数，过滤掉History标签
    return tabItems
      .map((group) => group.filter((item) => item.name !== 'History'))
      .filter((group) => group.length > 0); // 移除空组
  });

  const router = useRouter();
  const route = useRoute();
  const userStore = useUserStore();

  const isPro = computed(() => userStore.user?.user_type === 1);
  const rawRoute = computed(() => route.path === '/generator/history');
  // 获取当前活动的tab项
  const currentTab = computed(() => {
    // 扁平化tabItems数组以便查找
    const allTabItems = tabItems.flat();
    // 查找匹配当前路由的tab项
    const activeTab = allTabItems.find((item) => route.path.startsWith(item.path));
    // 如果找到则返回，否则返回默认对象
    return activeTab || { name: '' };
  });

  useBus().on('open:post', ({ image, prompt }) => {
    publishImageList.value = [image];
    promptText.value = prompt;
    contestTitle.value = activityDetail.value?.tag_name || '';

    openPublishDialog(true);
  });

  const openProPublishDialog = () => {
    publishImageList.value = [];
    openPublishDialog(false);
  };

  // 添加返回上一页的方法
  const goHome = () => {
    // router.replace('/');
    router.go(-1);
  };

  const goHomePage = () => {
    if (activityDetail.value) {
      router.replace('/contest/detail?aid=' + activityDetail.value.aid);
    } else {
      router.replace('/');
    }
  };

  // 导航到指定路由
  const navigateTo = (path: string) => {
    // 带上当前路由的查询参数进行跳转
    router.push({
      path: path,
      query: route.query,
    });
  };

  // 检查当前路由是否为激活状态
  const isActive = (path: string) => {
    // 检查当前路由是否以目标路径开头
    return route.path.startsWith(path);
  };

  // 打开发布对话框的方法
  const openPublishDialog = (mode: boolean) => {
    promptMode.value = mode;
    showPublishDialog.value = true;
    // 调用PublishDialog组件的open方法
    publishDialogRef.value?.open();
  };

  // 处理对话框关闭事件的方法
  const handleDialogClose = () => {
    showPublishDialog.value = false;
  };

  const aiStore = useAiStore();

  // 控制ImageList的显示
  const isShowImageList = computed(() => {
    const currentPath = route.path;
    // 只在txt2img路由下显示ImageList
    return currentPath === '/generator/txt2img';
  });

  // 存储当前悬停的项
  const hoveredItem = ref('');

  // 根据项目状态获取图标名称
  const getIconName = (item: TabItem) => {
    // 激活状态优先级最高
    if (isActive(item.path)) {
      return item.icon + '_active';
    }
    // 其次是悬停状态
    if (hoveredItem.value === item.path) {
      return item.icon + '_hover';
    }
    // 默认状态
    return item.icon;
  };

  const activityDetail = ref<any>(null);
  // 获取活动详情
  const getActivityDetail = async () => {
    try {
      // 从路由获取aid参数
      const aid = router.currentRoute.value.query.aid as string;
      if (!aid) return;

      // 调用API获取活动详情
      const response = await ActivityAPI.getActivityDetail({ aid });

      // 存储活动详情数据
      activityDetail.value = response.data;
    } catch (error) {
      console.error('Failed to fetch activity detail:', error);
    }
  };

  onMounted(() => {
    getActivityDetail();
  });
</script>

<style lang="scss" scoped>
  @use '@/styles/variables' as *;

  .page {
    height: 100vh;
    overflow: hidden;
  }
  .flex_row {
    display: flex;
    flex-direction: row;
  }
  .flex_col {
    display: flex !important;
    flex-direction: column !important;
  }
  .center_guide {
    justify-content: center;
  }
  .modal_guide {
    display: flex;
    flex-direction: row;
    .modal_left {
      background: #fff;
      height: 100px;
      padding: 0 8px;
      border-radius: 4px;
      align-self: flex-start;
    }
    .modal_flex_left {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      height: 100%;
    }
    .step_img3 {
      width: 480px;
      height: 534px;
    }
    .step_img4 {
      max-width: 1240px;
      max-height: 400px;
      border-radius: 4px;
      overflow: hidden;
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
  .header {
    width: 100%;
    height: 64px;
    display: flex;
    align-items: center;
    user-select: none;
    background: #fff;
    .logo {
      width: 80px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-right: 1px solid $primary-border-color;
      cursor: pointer; // 设置鼠标指针为手形

      // 添加悬停效果
      &:hover {
        opacity: 0.8;
        transition: opacity 0.3s ease;
      }
    }
    .title {
      font-size: 15px;
      padding: 0 24px;
      .bold {
        border-radius: 32px;
        background-color: #222222;
        color: #fff;
        padding: 0 12px;
      }
    }
    .name {
      margin-left: 16px;

      font-weight: 600;
      font-style: SemiBold;
      font-size: 16px;
      line-height: 100%;
      letter-spacing: 0%;
    }
    .aracde {
      padding-left: 16px;
      height: 32px;
      border-left: 1px solid $primary-border-color;
      line-height: 32px;
    }
  }
  .layout {
    display: flex;
    height: calc(100vh - 64px);
    .router-view {
      flex: 1;
      position: relative;
    }
  }
  .tab {
    width: 80px;
    display: flex;
    flex-direction: column;
    align-items: center;
    border-top: 1px solid $primary-border-color;
    border-right: 1px solid $primary-border-color;
    background-color: white;

    .tab-group {
      width: 32px;
      padding: 40px 0;
      border-bottom: 1px solid $primary-border-color;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s ease;

      &:last-child {
        border-bottom: none;
      }
    }
    .tab-item {
      margin-bottom: 34px;
      display: flex;
      justify-content: center;
      &:last-child {
        margin-bottom: 0;
      }

      // 鼠标悬停效果
      &:hover img {
        // 如果有悬停状态图标，这里可以添加过渡效果
        transition: all 0.3s ease;
      }

      // 激活状态样式
      &.active {
        // 激活状态的额外样式
      }
    }

    // 为img元素添加过渡效果
    img {
      transition: all 0.3s ease;
    }

    .publish-btn {
      position: absolute;
      bottom: 40px;
      left: 4px;
      cursor: pointer;
      &:hover {
        opacity: 0.9;
      }
    }
  }

  // 嵌套布局样式
  .nested-layout {
    display: flex;
    height: 100%;
  }
  .content-left {
    width: 480px;
    background-color: white;
  }
  .content-right {
    flex: 1;
    overflow-y: auto;
    height: calc(100vh - 64px);
  }
  .guide_view {
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>

<style lang="scss">
  .delete-confirm-dialog {
    padding: 24px;
    width: 480px;
    max-width: 480px;
    .el-message-box__title {
      font-weight: 500;
    }
    .el-message-box__message p {
      font-size: 14px;
      color: #7a7a7a;
      margin-bottom: 14px;
    }
    .el-button {
      width: 208px;
      background: #ededed;
      outline: none;
      color: #222222;
      border: none;
      height: 36px;
      &:hover {
        background: #e1e2e3;
      }
    }
    .el-button--primary {
      color: #fff;
      background: linear-gradient(90deg, #f76b1b 0%, #dc3a0e 100%);
      &:hover {
        background: linear-gradient(90deg, #f78647 0%, #e1603d 100%);
      }
    }
  }
</style>
